import { getToken } from '@/utils/storage'
import Article from '@/views/Article.vue'
import Collect from '@/views/Collect.vue'
import Detail from '@/views/Detail.vue'
import Layout from '@/views/Layout.vue'
import Like from '@/views/Like.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import User from '@/views/User.vue'
import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  { path: '/Login', component: Login },
  { path: '/Register', component: Register },
  { path: '/article/:id', component: Detail },
  {
    path: '/',
    // 重定向
    redirect: '/Article',
    component: Layout,
    children: [
      { path: 'Article', component: Article },
      { path: 'Collect', component: Collect },
      { path: 'Like', component: Like },
      { path: 'User', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whileList = ['/Login', '/Register']
router.beforeEach((to, form, next) => {
  const token = getToken()
  if (token) {
    next()
  } else if (whileList.includes(to.path)) {
    next()
  } else {
    Toast('请先登录')
    next('/Login')
  }
})

export default router
